package com.xuecheng.content.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mapper.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private TeachplanService teachplanService;//课程计划

    @Autowired
    private CourseBaseService courseBaseService;//课程基本信息

    @Autowired
    private BasicClient basicClient;//feign

    //课程预览
    @Override
    public Map preview(Long courseBaseId) {
        //校验前端参数
        if (courseBaseId==null){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //查询课程计划
        ResponseResult<TeachplanVo> responseResult = teachplanService.treeNodes_stream(courseBaseId);
        TeachplanVo teachplanVo = responseResult.getData();
        //查询课程基本信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //课程基本信息转为课程发布对象
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        //补全发布信息
        coursePub.setCourseId(courseBaseId);//课程id
        String mtName = getCategoryId(coursePub.getMt());//大分类
        coursePub.setMtName(mtName);
        String stName = getCategoryId(coursePub.getSt());//小分类
        coursePub.setStName(stName);
        coursePub.setTeachplan(JSON.toJSONString(teachplanVo));//课程计划
        coursePub.setPrice(courseBase.getPrice().longValue());//价格
        coursePub.setCreateDate(new Date());//创建时间
        //填充model
        Map model = new HashMap<>();
        model.put("coursePub",coursePub);//课程发布对象
        model.put("teachplanNode",teachplanVo);//课程计划
        //返回model
        return model;
    }

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private AsyncCoursePubService asyncCoursePubService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //课程发布
    @Override
    @Transactional
    public ResponseResult publish(Long courseBaseId) throws Exception{
        //校验前端参数
        if (courseBaseId==null){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //查询课程信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //校验课程状态 审核通过的才能发布
        if (!StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PASTED_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //从model中获取课程发布对象
        Map preview = this.preview(courseBaseId);
        CoursePub coursePub = (CoursePub) preview.get("coursePub");
        //写入数据库
        this.save(coursePub);
        //更新课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);
       /* //FreeMaker生成HTML
        //加载模板
        Template template = configuration.getTemplate("learing_article.ftl");
        //输出HTML文件
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, preview);
        //HTML文本转为io流
        ByteArrayInputStream inputStream = IoUtil.toStream(content.getBytes());
        //保存至minio
        minioTemplate.uploadHtml(inputStream,courseBaseId+".html");*/
        //异步调用
        asyncCoursePubService.publish(preview,courseBaseId);
        //发送异步mq消息 发送课程id
        rabbitTemplate.convertAndSend("content-exchange","course.pub",coursePub.getId());
        //返回200
        return ResponseResult.okResult();
    }

    // feign查询分类
    private String getCategoryId(String categoryId) {
        //远程调用
        ResponseResult<CategoryVo> categoryVoResponseResult = basicClient.findById(categoryId);
        //判断调用是否正常
        if (categoryVoResponseResult.getCode()!=0) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //获取分类
        CategoryVo categoryVo = categoryVoResponseResult.getData();
        String name = categoryVo.getName();
        return name;
    }
}
